from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
from user_abt.models import UserInfo, Rsa_Key, Session_Self
from user_abt.login_y import login_required
from django.db.models import Q   # 多条件查询
import requests
import random
from django_redis import get_redis_connection     # 连接redis
from s_encipher.encipher_rsa import decrypt_data  # 解密函数
from return_data.return_data import return_data

# Create your views here.
"""
生成验证码视图
技术点：使用redis缓存sms和手机号，并在5分钟后删除
"""
@require_http_methods(['OPTIONS','POST'])
def sendphone(request):
    """前端获取的数据,是bytes"""
    if request.method == 'POST':
        phonenum = eval(str(request.body, encoding='utf-8'))['data']['phone']
        # print(phonenum, type(phonenum))
        """判断手机号是否已注册"""
        if UserInfo.objects.filter(user_phone=phonenum).first():
            status = 4001
            message = '手机号已注册'
            # return HttpResponse('手机号已注册')
            # print("4001里")
        else:
            """生成并发送6验证码"""
            # sms = random.randint(100000, 999999)
            # print(sms)
            sms = 363636
            """
            连接redis，存储phone为键，值为sms string类型。键的有效期设置为五分钟
            """
            conn = get_redis_connection('default')
            conn.set(phonenum, sms)
            conn.expire(phonenum, 300) # 5分钟后过期

            """向三方短信验证api请求  params是上传的参数：sms，电话号码，headers是平台登录验证"""
            # r = requests.get('https://feginesms.market.alicloudapi.com/codeNotice',
            #                  params={'param': f'{sms}', 'phone': f'{phonenum}', 'sign': '175622', 'skin': '8'},
            #                  headers={"Authorization": "APPCODE 448089275aeb4455ae54434ce7a00b7a"})
            # print(r)
            # return HttpResponse(200)
            status = 0
            message = "验证码发送成功，注意查收"
            # print("0里")

        ret = return_data(status, message, {})
        return HttpResponse(ret)
    else:
        return HttpResponse(200)

@require_http_methods(['OPTIONS', 'GET'])
def get_public(request):
    if request.method == 'GET':
        keys = Rsa_Key.objects.all().first()
        pubkey = keys.pub_key
        print(pubkey)
        return HttpResponse(pubkey)
    else:
        return HttpResponse(200)


@require_http_methods(['OPTIONS','POST'])
def register(request):
    if request.method == 'POST':
        """
        data是前端传来的数据，包括手机号，邮箱，密码，验证码
        在这个视图要完成对以上数据的验证（手机号、邮箱是否已注册，验证码是否正确）
        如果验证全部完成，则将用户信息存入数据库UserInfo，否则返回相应的提示。
        技术点1、用户信息加密，前端就要加密传输到后端，选择非对称加密。
                a、前端请求数据前先想后端发送请求获取公钥。
                b、后端生成公钥和私钥，公钥发送给前端作加密用，私钥留在服务器上作解密用
              2、数据序列化返回。返回注册失败成功的信息。
        """
        data = eval(str(request.body, encoding='utf-8'))['data']
        # print(data,len(data),type(data))
        # 私钥
        keys = Rsa_Key.objects.all().first()
        prikey = keys.pri_key
        # 解密
        # data = decrypt_data(data, prikey)
        # print(data)
        """
        对前端发送过来的数据进行一个解密，然后进行判断手机号与邮箱是否已经注册
        """
        data = {key: decrypt_data(value, prikey) for key, value in data.items()}
        
        """取出sms，如果在点注册按钮前没有获取验证码会直接返回 请先获取验证码"""
        try:
            conn = get_redis_connection('default')
            sms = conn.get(data['phone']).decode()
            print(sms)
        except AttributeError as a:
            message = '请先获取验证码'
            status = 4005
            ret = return_data(status, message, {})
            return HttpResponse(ret)

        # print(data)
        if UserInfo.objects.filter(user_phone=data['phone']).first():
            message = '手机已注册'
            status = 4001
        elif UserInfo.objects.filter(user_email=data['email']).first():
            message = '邮箱已注册'
            status = 4002
        elif data['sms'] != sms:
            message = '验证码错误'
            status = 4003
        else:
            """默认注册时默认昵称设置为邮箱前缀"""
            name = data['email'].split('@')[0]
            user = UserInfo(user_name=name, user_email=data['email'], user_phone=data['phone'], user_passwd=data['password'])
            user.save()
            message = '注册成功,点击确定跳转到登录页面。'
            status = 0
        ret = return_data(status, message, {})
        return HttpResponse(ret)
    else:
        return HttpResponse('ok')


@require_http_methods(['OPTIONS','POST'])
def login(request):
    if request.method == 'POST':
        # print(request.headers['Sessionid'])
        data = eval(str(request.body, encoding='utf-8'))['data']
        keys = Rsa_Key.objects.all().first()
        prikey = keys.pri_key
        usename = decrypt_data(data['usename'], prikey)
        password = decrypt_data(data['password'], prikey)
        # print(usename,password)
        """
        验证账号密码，账号可能是手机号也可能是邮箱。
        """
        user = UserInfo.objects.filter(Q(user_phone=usename) | Q(user_email=usename)).first()
        if user:
            if password == user.user_passwd:
                # print('密码正确')
                message = "登录成功"
                status = 0

                """session写法，失败了"""
                # """记录用户的登录状态,用户信息ID"""
                # request.session['userid'] = user.id
                # request.session['is_login'] = True
                # ret = return_data(status, message, {})
                # res = HttpResponse()
                # res.content = ret
                # res.set_cookie('userid',user.id, expires=1209600)
                # print(request.session.get('userid'))
                # return res
                """自建session写法"""
                session_self = Session_Self(sessionid=str(user.id)+str(random.randint(1000, 9999)), userid=user.id, userstatus='login')
                session_self.save()
                data = {'sessionid':session_self.sessionid, 'userstatus':session_self.userstatus}
                ret = return_data(status, message, data)
                return HttpResponse(ret)

            else:
                # print('密码不正确')
                message = "密码不正确"
                status = 4012
        else:
            # print('账号不存在')
            message = "账号不存在"
            status = 4011
        # print(request.body)
        # print(data)
        ret = return_data(status, message, {})
        return HttpResponse(ret)
    else:
        return HttpResponse('ok')


def change_info(request):
    return HttpResponse('ok')


@login_required
@require_http_methods(['OPTIONS','GET'])
def check_out(request):
    if request.method=='OPTIONS':
        return HttpResponse(200)
    else:
        sessionid = request.headers['sessionid']
        # print(request.headers)
        print(sessionid, type(sessionid))
        Session_Self.objects.filter(sessionid=sessionid).first().delete()
        return HttpResponse('ok')